package com.gitee.huanminabc.fastboot.load.stage;

import com.gitee.huanminabc.jcommon.multithreading.executor.ThreadFactoryUtil;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.context.AppContextUtil;
import com.gitee.huanminabc.fastboot.load.stage.poststage.AppLoadPostStage;
import com.gitee.huanminabc.fastboot.load.stage.poststage.ConfigValueInjectionStage;
import com.gitee.huanminabc.fastboot.load.stage.poststage.ContainerInitCallBackStage;
import com.gitee.huanminabc.fastboot.load.stage.poststage.DependencyInjectionStage;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description:
 * @author: huanmin
 * @create: 2025-04-08 18:01
 **/
@Slf4j
public class PostStageLauncher {
   public final static List<AppLoadPostStage> appLoadStages = new ArrayList<>();
    static {
        appLoadStages.add(new DependencyInjectionStage());
        appLoadStages.add(new ConfigValueInjectionStage());
        appLoadStages.add(new ContainerInitCallBackStage());

    }
    public void load() {
        AppContextUtil.orderSort(appLoadStages);
        
        ThreadPoolExecutor executor = ThreadFactoryUtil.getDefaultExecutor();
        CountDownLatch countDownLatch = new CountDownLatch(appLoadStages.size());
        for (AppLoadStage appLoadStage : appLoadStages) {
            if (!appLoadStage.isRun()) {
                continue;
            }
            //异步加载
            executor.execute(() -> {
                AppContext.taskTimeWatch.start(appLoadStage.getClass().getSimpleName()+"耗时");
                try {
                    appLoadStage.run();
                } catch (Exception e) {
                    log.error("PostStageLauncher:", e);
                    System.exit(1);
                } finally {
                    AppContext.taskTimeWatch.stop();
                    countDownLatch.countDown();

                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("PostStageLauncher:", e);
            System.exit(1);
        }
    }
}
